﻿using BLL;
using Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Collections;

namespace Student
{
    public partial class select_Group : Form
    {

        List<g_display> gds;
        List<g_display> selected_groups = new List<g_display>();
        t_data m_t;
        List<Models.Student> all_student;
        List<Color> colors = new List<Color>();
        //List<int> spare_idx = new List<int>();
        Hashtable used_idx = new Hashtable();
        int[] unused = new int[10];

        public select_Group()
        {
            InitializeComponent();

            colors.Add(Color.Green);
            colors.Add(Color.Red);
            colors.Add(Color.Orange);
            colors.Add(Color.Orchid);
            colors.Add(Color.Purple);
            colors.Add(Color.Pink);
            colors.Add(Color.Red);
            colors.Add(Color.Orchid);
            colors.Add(Color.AliceBlue);
            colors.Add(Color.Blue);
        }

        // 定义鼠标点击事件的处理方法
        private void student_list_MouseClick(object sender, MouseEventArgs e)
        {
            // 如果当前没有选中的单元格，则不执行任何操作
            if (group_list.CurrentCell == null) return;

            // 获取当前选中单元格的行索引
            int idx = group_list.CurrentCell.RowIndex;

            // 将Group_name文本框的内容设置为当前行的group_name
            Group_name.Text = gds[idx].group_name;

            // 将Project_name文本框的内容设置为当前行的project_name
            Project_name.Text = gds[idx].project_name;

            // 将Group_info文本框的内容设置为当前行的project_info
            Group_info.Text = gds[idx].project_info;

            // 从all_student集合中筛选出group_id等于当前行g_id的所有学生
            var g_members = all_student.Where(stu => stu.group_id == gds[idx].g_id).ToList();

            // 将Group_members控件的数据源设置为筛选出的学生列表
            Group_members.DataSource = g_members;
            //Group_members.Columns[0].Visible = false;
            Group_members.Columns["pwd"].Visible = false;
            Group_members.Columns["major_id"].Visible = false;

            Group_members.Columns["stu_id"].HeaderText = "学生ID";
            Group_members.Columns["stu_no"].HeaderText = "学号";
            Group_members.Columns["stu_name"].HeaderText = "姓名";
            Group_members.Columns["grade"].HeaderText = "年级";
            Group_members.Columns["phone"].HeaderText = "电话";
            Group_members.Columns["group_id"].HeaderText = "学生组ID";
            Group_members.Columns["is_gleader"].HeaderText = "是否为组长";
        }


        private int get_tChoice(Models.t_data t_Data, string pro_name)
        {
            return (int)(t_Data.GetType().GetProperty(pro_name).GetValue(t_Data, null)??-1);
        }

        private void set_tChoice(Models.t_data t_Data, string pro_name, int g_id)
        {
            t_Data.GetType().GetProperty(pro_name).SetValue(t_Data, g_id);
        }

        // 定义一个窗体加载事件处理方法，当窗体加载时调用
        private void select_student_Load(object sender, EventArgs e)
        {
            // 创建BLL层的B_g_display对象，用于获取组的显示信息
            BLL.B_g_display b_G_Display = new BLL.B_g_display();
            // 调用GetList方法获取所有组的列表，并赋值给gds变量
            gds = b_G_Display.GetList();

            gds = b_G_Display.GetList()
               // .Where(g => g.Teacher_1 == log_info.teacher.teacher_name || g.Teacher_2 == log_info.teacher.teacher_name || g.Teacher_3 == log_info.teacher.teacher_name ||
               //  g.Teacher_4 == log_info.teacher.teacher_name || g.Teacher_5 == log_info.teacher.teacher_name)
    .OrderBy(g => g.Teacher_1 == log_info.teacher.teacher_name ? 0 : 1)
    .ThenBy(g => g.Teacher_2 == log_info.teacher.teacher_name ? 0 : 1)
    .ThenBy(g => g.Teacher_3 == log_info.teacher.teacher_name ? 0 : 1)
    .ThenBy(g => g.Teacher_4 == log_info.teacher.teacher_name ? 0 : 1)
    .ThenBy(g => g.Teacher_5 == log_info.teacher.teacher_name ? 0 : 1)
    .ToList();
            group_list.DataSource = gds;

            // 将group_list控件的数据源设置为gds，显示所有组的信息
            group_list.DataSource = gds;

            //group_list.Columns[11].Width = 1;


            // 循环设置group_list的前9列不可见
            for (int i = 0; i < 9; i++)
            {
                group_list.Columns[i].Visible = false;
            }
            
            //group_list.Columns[11].Visible = false;
            group_list.Columns[15].Visible = false;
            group_list.Columns[16].Visible = false;

            group_list.Columns[9].HeaderText = "项目名称";
            group_list.Columns[10].HeaderText = "队伍名称";
            group_list.Columns[11].HeaderText = "第一志愿";
            group_list.Columns[12].HeaderText = "第二志愿";
            group_list.Columns[13].HeaderText = "第三志愿";
            group_list.Columns[14].HeaderText = "简介";

            // 创建BLL层的B_Student对象，用于获取学生信息
            BLL.B_Student b_student = new BLL.B_Student();
            // 调用GetList方法获取所有学生的信息，并赋值给all_student变量
            all_student = b_student.GetList();

            // 循环初始化未使用的索引和已选择的组
            for (int i = 0; i < log_info.Sys_Config.tearch_choice; i++)
            {
                // 初始化未使用的索引数组
                unused[i] = 1;
                // 添加一个新的g_display对象到已选择的组列表
                selected_groups.Add(new g_display());
            }
            // 将selected_Group控件的数据源设置为selected_groups的BindingList
            selected_Group.DataSource = new BindingList<g_display>(selected_groups);
            selected_Group.Columns["project_info"].MinimumWidth =250;

            // 循环设置selected_Group的前9列不可见
            for (int i = 0; i < 9; i++)
                selected_Group.Columns[i].Visible = false;

            selected_Group.Columns[15].Visible = false;
            selected_Group.Columns[16].Visible = false;
            
            selected_Group.Columns[9].HeaderText = "项目名称";
            selected_Group.Columns[10].HeaderText = "队伍名称";
            selected_Group.Columns[11].HeaderText = "第一志愿";
            selected_Group.Columns[12].HeaderText = "第二志愿";
            selected_Group.Columns[13].HeaderText = "第三志愿";
            selected_Group.Columns[14].HeaderText = "简介";

            // 创建B_T对象，用于获取教师信息
            B_T b_T = new B_T();
            // 调用select方法获取当前教师的信息，并赋值给m_t变量
            m_t = b_T.select(log_info.teacher);

            // 如果m_t为null，说明没有获取到教师信息，创建一个新的t_data对象并返回
            if (m_t == null)
            {
                m_t = new Models.t_data();
                return;
            }

            // 循环处理每个教师选择的组
            for (int i = 1; i <= log_info.Sys_Config.tearch_choice; i++)
            {
                // 获取教师选择的第i个组的索引
                var choice = get_tChoice(m_t, $"c{i}");
                // 如果选择的索引有效
                if (choice != -1)
                {
                    // 根据选择的索引获取对应的组
                    var t_grps = gds.Where(g => g.g_id == choice);
                    // 如果没有找到对应的组
                    if (t_grps.Count() == 0)
                    {
                        // 将教师的选择设置为-1（无效）
                        set_tChoice(m_t, $"c{i}", -1);
                        // 继续下一个循环
                        continue;
                    }

                    // 获取在gds中对应的行索引
                    var row_idx = gds.FindIndex(item => item == t_grps.First());

                    // 更新已选择的组列表
                    selected_groups[i - 1] = gds[row_idx];
                    // 设置对应的行背景颜色
                    group_list.Rows[row_idx].DefaultCellStyle.BackColor = colors[i - 1];
                    // 将行索引添加到已使用的索引列表
                    used_idx.Add(row_idx, i - 1);
                    // 将未使用的索引标记为已使用
                    unused[i - 1] = 0;
                }
            }
        }

        //private void 提交_Click(object sender, EventArgs e)
        //{
        //    if(log_info.sys_Configs[0].teacher_deadline < log_info.Server_Time)
        //    {
        //        MessageBox.Show("已经超时，不能再修改！");
        //        return;
        //    }


        //    int tmp_gid;
        //    for (int i = 0; i < log_info.Sys_Config.tearch_choice; i++)
        //    {
        //        tmp_gid = (int)selected_groups[i].g_id == 0 ? -1: (int)selected_groups[i].g_id;
        //        set_tChoice(m_t, $"c{i+1}", tmp_gid);
        //    }

        //    m_t.t_id = log_info.teacher.teacher_id;
        //    BLL.B_T b_T = new BLL.B_T();
        //    if(b_T.commit(m_t))
        //        MessageBox.Show("ok!");

        //}

        private void group_list_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (group_list.CurrentCell == null) return;

            select_one(group_list.CurrentCell.RowIndex);
        }

        private void select_one(int idx)
        {
            int tmp_idx;

            if(used_idx.ContainsKey(idx))
            {
                tmp_idx = (int)used_idx[idx];
                selected_groups[tmp_idx] = new g_display();
                used_idx.Remove(idx);
                unused[tmp_idx] = 1;
                group_list.Rows[idx].DefaultCellStyle.BackColor = System.Drawing.SystemColors.Window;
            }
            else
            {
                if (used_idx.Count == log_info.Sys_Config.tearch_choice)
                {
                    MessageBox.Show("不能选更多的组！");
                    return;
                }
                for(int i = 0; i < log_info.Sys_Config.tearch_choice; i++)
                {
                    if (unused[i]==1)
                    {
                        unused[i] = 0;
                        used_idx.Add(idx, i);
                        selected_groups[i] = gds[idx];
                        group_list.Rows[idx].DefaultCellStyle.BackColor = colors[i];
                        break;
                    }
                }
            }

            selected_Group.DataSource = new BindingList<g_display>(selected_groups);
        }

        private void selected_Group_MouseClick(object sender, MouseEventArgs e)
        {
            // int idx = selected_Group.CurrentCell.RowIndex;
            //if (!Tools.Check.IsIndexInRange(gds, idx))
            //     return;
            // Group_name.Text = gds[idx].group_name;
            // Project_name.Text = gds[idx].project_name;
            // Group_info.Text = gds[idx].project_info;
            //
            // var g_members = all_student.Where(stu => stu.group_id == gds[idx].g_id).ToList();
            // Group_members.DataSource = g_members;

            int idx = selected_Group.CurrentCell.RowIndex;
            if (idx < 0 || idx >= selected_groups.Count) return; // 检查索引是否在selected_groups的范围内
        
            // 直接从selected_groups中获取队伍信息
            var selectedGroup = selected_groups[idx];
            Group_name.Text = selectedGroup.group_name;
            Project_name.Text = selectedGroup.project_name;
            Group_info.Text = selectedGroup.project_info;
        
            // 从all_student中筛选出selectedGroup.g_id对应的学生
            var g_members = all_student.Where(stu => stu.group_id == selectedGroup.g_id).ToList();
            Group_members.DataSource = g_members;
            // 更新列的可见性和标题
            //Group_members.Columns[0].Visible = false;
            Group_members.Columns[2].Visible = false;
            Group_members.Columns[4].Visible = false;

            Group_members.Columns[0].HeaderText = "学生ID";
            Group_members.Columns[1].HeaderText = "学号";
            Group_members.Columns[3].HeaderText = "姓名";
            Group_members.Columns[5].HeaderText = "年级";
            Group_members.Columns[6].HeaderText = "电话";
            Group_members.Columns[7].HeaderText = "学生组ID";
            Group_members.Columns[8].HeaderText = "是否为组长";
        }


        private void selected_Group_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,e.RowBounds.Location.Y,
                                                selected_Group.RowHeadersWidth - 4,e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            selected_Group.RowHeadersDefaultCellStyle.Font,
            rectangle,
            selected_Group.RowHeadersDefaultCellStyle.ForeColor,
            TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void Group_info_TextChanged(object sender, EventArgs e)
        {

        }

        private void sTreturn1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            if (log_info.sys_Configs[0].teacher_deadline < log_info.Server_Time)
            {
                MessageBox.Show("已经超时，不能再修改！");
                return;
            }


            int tmp_gid;
            for (int i = 0; i < log_info.Sys_Config.tearch_choice; i++)
            {
                tmp_gid = (int)selected_groups[i].g_id == 0 ? -1 : (int)selected_groups[i].g_id;
                set_tChoice(m_t, $"c{i + 1}", tmp_gid);
            }

            m_t.t_id = log_info.teacher.teacher_id;
            BLL.B_T b_T = new BLL.B_T();
            if (b_T.commit(m_t))
                MessageBox.Show("ok!");
        }
    }
}
